﻿using Microsoft.Extensions.DependencyInjection.Extensions;
using Puppy.ActorDb;
using System;

namespace Microsoft.Extensions.DependencyInjection
{
    public static class ActorDbServiceCollectionExtensions
    {
        public static IServiceCollection AddActorDbContext<TActorDbContext>(this IServiceCollection services, Action<IActorDbContextRegistrationOptionsBuilder> optionsBuilder = null)
            where TActorDbContext : ActorDbContext
        {
            var options = new ActorDbContextRegistrationOptions(typeof(TActorDbContext), services);
            optionsBuilder?.Invoke(options);

            services.TryAddTransient(typeof(IActorDatabaseProvider<>), typeof(ActorDatabaseProvider<>));

            if (options.DefaultRepositoryDbContextType != typeof(TActorDbContext))
            {
                services.TryAddSingleton(options.DefaultRepositoryDbContextType, sp => sp.GetRequiredService<TActorDbContext>());
            }

            foreach (var dbContextType in options.ReplacedDbContextTypes)
            {
                services.Replace(ServiceDescriptor.Singleton(dbContextType, sp => sp.GetRequiredService<TActorDbContext>()));
            }

            new ActorDbRepositoryRegistrar(options).AddRepositories();

            return services;
        }
    }
}
